package com.lancoo.klgcourseware.manager;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.appcompat.app.AlertDialog;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.android.tu.loadingdialog.LoadingDailog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.api.KlgEnglishApi;
import com.lancoo.klgcourseware.api.PassTrainApi;
import com.lancoo.klgcourseware.entity.EnglishCardSource;
import com.lancoo.klgcourseware.entity.ExpressionAndUsageModel;
import com.lancoo.klgcourseware.entity.KlgApiResponse;
import com.lancoo.klgcourseware.entity.ObsConfigMsgBean;
import com.lancoo.klgcourseware.entity.ResourcePlatFormConfigure;
import com.lancoo.klgcourseware.entity.WordExplainModel;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.entity.passTrain.PassTrainResponce;
import com.lancoo.klgcourseware.entity.passTrain.WordBookRequestBean;
import com.lancoo.klgcourseware.ui.activity.KlgCourseWareMainActivity;
import com.lancoo.klgcourseware.ui.widget.VolumeAlignImageSpan;
import com.lancoo.klgcourseware.utils.KlgToolUtils;
import com.lancoo.klgcourseware.utils.KlgUrlEncodeUtils;
import com.lancoo.klgcourseware.utils.UniCodeUtils;
import com.lancoo.klgcourseware.utils.klog.KLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.RxApiManager;
import lancoo.com.net.retrofitrxjava.download.FileDownLoadObserver;
import lancoo.com.net.retrofitrxjava.download.HttpDownManager;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;

/**
 * Created by pengmi on 2019/8/19 9:35
 * Description:知识点卡片弹窗管理器
 */
public class KlgCardDialogManager implements View.OnClickListener {

    public static KlgCardDialogManager klgCardDialogManager;
    private long time;
    private KlgMediaManager klgMediaManager;
    private ImageView img_usPhonetic,img_unPhonetic,img_senPhonetic;
    private AlertDialog klgCardDialog;
    protected LoadingDailog loadingDailog;
    private boolean isLoad;
    private CustomBtnClickListener mCustomBtnClickListener;
    private LinearLayout ll_unPhonetic,ll_usPhonetic;
    private RelativeLayout ll_sentenceStructures;
    private TextView tv_explain;
    private ImageView img_arrorLeft,img_arrorRight;
    private int currentKlgIndex,dissMissType;
    private View inflate;
    private List<KlgCommonBean> klgCommonBeanList;
    private VolumeAlignImageSpan centerAlignImageSpan;
    private TextView tv_sentenceStructures;

    private KlgCardDialogManager() {
    }

    public static KlgCardDialogManager getInstance(){
        if(klgCardDialogManager==null){
            klgCardDialogManager=new KlgCardDialogManager();
        }
        return klgCardDialogManager;
    }



    /**
     * 展示知识点弹窗,非电子教材库调用
     * @param mContext
     * @param commonBean
     * @param isRetractCard 内部调用访问标志 true-基础训练调用  false-其他模块调用
     */
    public void showKnowledgeCardDialog(final Context mContext, final KlgCommonBean commonBean, boolean isRetractCard, boolean hasCustomBtn,
                                        final KlgCardDismissListener listener){
//        showKnowledgeCardDialog(mContext,commonBean,isRetractCard,hasCustomBtn,listener,true);
        showKnowledgeCardDialog(mContext,commonBean,isRetractCard,true,listener,false,false,"");
    }



    /**
     * 展示知识点弹窗,电子教材库专用
     * @param mContext
     * @param commonBean
     * @param isRetractCard 内部调用访问标志 true-基础训练调用  false-其他模块调用
     */
    public void showKnowledgeCardDialog(final Context mContext, final KlgCommonBean commonBean, final boolean isRetractCard,
                                        boolean hasCustomBtn, final KlgCardDismissListener listener,boolean hasSave,boolean hasNote,
                                        String customBtnName){
        if(KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.getInstance().showTrainAgainDialog(mContext);
            return;
        }
        currentKlgIndex=0;
        dissMissType=0;
        if(commonBean==null){
            showNoKlgDetailsDialog(mContext);
            return;
        }
        KLog.json(JSON.toJSONString(commonBean));
        Log.e("aaaa","json:"+JSON.toJSONString(commonBean));
        if(isRetractCard){
            mCustomBtnClickListener=null;
            hasCustomBtn=false;
        }
        inflate = LayoutInflater.from(mContext).inflate(R.layout.klg_dialog_card_word, null);
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext,R.style.klg_NoBgColorStyle);
        builder.setView(inflate);
        klgCardDialog = builder.create();
        klgCardDialog.show();

        Window window = klgCardDialog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        int screenWidth=KlgToolUtils.getWidthInPx(mContext);
        int width=0;
        int height=0;
        int imgHeight=KlgToolUtils.dip2px(mContext,50);
        if(KlgToolUtils.isPad(mContext)){
            width=KlgToolUtils.dip2px(mContext,1395/3);
            height=KlgToolUtils.dip2px(mContext,1000/3)+(hasSave?imgHeight:0);
            if(screenWidth<=width){
                width=screenWidth;
            }
        }else{
            width=KlgToolUtils.dip2px(mContext,953/3)*1092/953;
            height=KlgToolUtils.dip2px(mContext,953/3)+(hasSave?imgHeight:0);
            if(screenWidth<=width){
                width=screenWidth;
            }
        }

        attributes.height= height;
        attributes.width=width;
        attributes.dimAmount=0.3f;
        window.setAttributes(attributes);
        RelativeLayout rl_head = inflate.findViewById(R.id.rl_head);
        ViewGroup.LayoutParams layoutParams = rl_head.getLayoutParams();
        if(KlgToolUtils.isPad(mContext)){
            layoutParams.height=KlgToolUtils.dip2px(mContext,1202/3)*65/300;
        }else{
            layoutParams.height=KlgToolUtils.dip2px(mContext,953/3)*76/280;
        }
        rl_head.setLayoutParams(layoutParams);
        LinearLayout ll_bottom = inflate.findViewById(R.id.ll_bottom);
        ViewGroup.LayoutParams layoutParams2 = ll_bottom.getLayoutParams();

        if(KlgToolUtils.isPad(mContext)){
            layoutParams2.height=KlgToolUtils.dip2px(mContext,1202/3)*35/300;
        }else{
            layoutParams2.height=KlgToolUtils.dip2px(mContext,953/3)*38/280;
        }
        ll_bottom.setLayoutParams(layoutParams2);
        NestedScrollView nestedScrollView = inflate.findViewById(R.id.scroll_view);
        ViewGroup.LayoutParams layoutParams3 =nestedScrollView.getLayoutParams();
        if(KlgToolUtils.isPad(mContext)){
            layoutParams3.height=KlgToolUtils.dip2px(mContext,1202/3)*117/300;
        }else{
            layoutParams3.height=KlgToolUtils.dip2px(mContext,953/3)*(140)/280;
        }
        nestedScrollView.setLayoutParams(layoutParams3);
        showFayinStyle(mContext,commonBean, inflate,isRetractCard);
        showWordMoreMessageStyle(mContext,commonBean, inflate,isRetractCard);
        showFayinViewStyle(mContext, inflate);
        showWordMsgViewStyle(mContext, inflate);
        View view = inflate.findViewById(R.id.ll_klg_card);
        view.setBackgroundResource(isRetractCard||hasSave?R.drawable.klg_icon_klg_card_no_close_bg:R.drawable.klg_icon_klg_card_bg);
        TextView tv_retractCard = inflate.findViewById(R.id.tv_retract_card);
        img_arrorLeft = inflate.findViewById(R.id.img_arror_left);
        img_arrorRight = inflate.findViewById(R.id.img_arror_right);
        img_arrorLeft.setOnClickListener(this);
        img_arrorRight.setOnClickListener(this);
        tv_retractCard.setText(isRetractCard?R.string.klg_retract_card:R.string.klg_courseware_study);
        if(commonBean.isHideBtn()){
            tv_retractCard.setVisibility(View.GONE);
            inflate.findViewById(R.id.view_divider_right).setVisibility(View.GONE);
        }else{
            tv_retractCard.setVisibility(View.VISIBLE);
            inflate.findViewById(R.id.view_divider_right).setVisibility(View.VISIBLE);
        }
        tv_retractCard.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(isRetractCard?R.mipmap.klg_icon_retract_card:R.mipmap.klg_icon_entry_courseware),null,null,null);
        inflate.findViewById(R.id.img_close).setEnabled(!(isRetractCard||hasSave));
        inflate.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(System.currentTimeMillis()-time<500){
                    return;
                }
                time=System.currentTimeMillis();
                dissMissType=0;
                if(klgCardDialog !=null&& klgCardDialog.isShowing()){
                    klgCardDialog.dismiss();
                }

            }
        });

        klgCardDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isLoad=false;
                if(listener!=null){
                    if(klgCommonBeanList!=null&&currentKlgIndex<klgCommonBeanList.size()){
                        listener.onCardDismiss(dissMissType,currentKlgIndex,klgCommonBeanList.get(currentKlgIndex),null);
                    }else{
                        listener.onCardDismiss(dissMissType,currentKlgIndex,commonBean,null);
                    }
                }
                if(klgMediaManager!=null){
                    klgMediaManager.pause();
                }
                if(loadingDailog!=null&&loadingDailog.isShowing()){
                    loadingDailog.dismiss();
                }
            }
        });
        if(hasCustomBtn||hasSave||hasNote){
            inflate.findViewById(R.id.view_add_restudy_weight).setVisibility(View.VISIBLE);
            TextView tv_addStudy = inflate.findViewById(R.id.tv_add_study);
            if(!TextUtils.isEmpty(customBtnName)){
                ((TextView)inflate.findViewById(R.id.tv_add_study)).setText(customBtnName);
            }else{
                if(hasNote){
                    tv_addStudy.setText(R.string.klg_make_note);
                    tv_addStudy.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(R.mipmap.klg_icon_make_note),null,null,null);
                }
                if(hasSave){
                    final ImageView img_save=inflate.findViewById(R.id.img_save);
                    img_save.setVisibility(View.VISIBLE);
                    img_save.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(System.currentTimeMillis()-time<500){
                                return;
                            }
                            time=System.currentTimeMillis();
                            dissMissType=-1;
                            if(listener!=null){
                                KlgCollectionWordCallBack callBack=new KlgCollectionWordCallBack() {
                                    @Override
                                    public void updateCollectionState(int state) {
                                        if(img_save!=null){
                                            img_save.setImageResource(state==1?R.mipmap.klg_icon_save_blue:R.mipmap.klg_icon_save_white);
                                        }
                                    }
                                };
                                if(klgCommonBeanList!=null&&currentKlgIndex<klgCommonBeanList.size()){
                                    listener.onCardDismiss(3,currentKlgIndex,klgCommonBeanList.get(currentKlgIndex),callBack);
                                }else{
                                    listener.onCardDismiss(3,currentKlgIndex,commonBean,callBack);
                                }
                            }
                        }
                    });
                    img_save.setImageResource(commonBean.getIsCollectWord()==0?R.mipmap.klg_icon_save_white:
                            R.mipmap.klg_icon_save_blue);
                    inflate.findViewById(R.id.img_close_x).setOnClickListener(this);
                    TextView tv_klgName = inflate.findViewById(R.id.tv_klg_name);
                    RelativeLayout.LayoutParams lp_klgName = (RelativeLayout.LayoutParams) tv_klgName.getLayoutParams();
                    lp_klgName.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    lp_klgName.addRule(RelativeLayout.LEFT_OF,R.id.img_save);
                }
            }
            inflate.findViewById(R.id.tv_add_study).setVisibility(View.VISIBLE);
            inflate.findViewById(R.id.tv_add_study).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(System.currentTimeMillis()-time<500){
                        return;
                    }
                    time=System.currentTimeMillis();
                    dissMissType=1;
                    if(klgCardDialog !=null&& klgCardDialog.isShowing()){
                        klgCardDialog.dismiss();
                    }
                    if(mCustomBtnClickListener!=null){
                        mCustomBtnClickListener.onCustomBtnClick(commonBean,v);
                    }
                }
            });
        }
        controlImgAnimation(false,false,false);
    }


    /**
     * 同时展示多个知识点弹窗 非电子教材库用
     * @param mContext
     * @param klgCommonBeanList
     * @param isRetractCard 内部调用访问标志 true-基础训练调用  false-其他模块调用
     */
    public void showMoreKnowledgeCardDialog(final Context mContext, final List<KlgCommonBean> klgCommonBeanList, final boolean isRetractCard, boolean hasCustomBtn, final KlgCardDismissListener listener){
        if(KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.getInstance().showTrainAgainDialog(mContext);
            return;
        }
        if(klgCommonBeanList!=null&&klgCommonBeanList.size()>0){
//            showKnowledgeCardDialog(mContext,klgCommonBeanList.get(0),isRetractCard,hasCustomBtn,listener);
            showKnowledgeCardDialog(mContext,klgCommonBeanList.get(0),isRetractCard,false,listener,false,false,"");
            if(klgCommonBeanList.size()==1){
                img_arrorLeft.setVisibility(View.INVISIBLE);
                img_arrorRight.setVisibility(View.INVISIBLE);
            }else{
                img_arrorLeft.setVisibility(View.INVISIBLE);
                img_arrorRight.setVisibility(View.VISIBLE);
                img_arrorLeft.setTag(klgCommonBeanList);
                img_arrorRight.setTag(klgCommonBeanList);
            }
        }else {
            showNoKlgDetailsDialog(mContext);
        }

    }
    /**
     * 同时展示多个知识点弹窗 电子教材库专用
     * @param mContext
     * @param klgCommonBeanList
     * @param isRetractCard 内部调用访问标志 true-基础训练调用  false-其他模块调用
     */
    public void showMoreKnowledgeCardDialog(final Context mContext, final List<KlgCommonBean> klgCommonBeanList,
                                            final boolean isRetractCard, boolean hasCustomBtn,
                                            final KlgCardDismissListener listener,boolean hasSave,boolean hasNote){
        if(KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.getInstance().showTrainAgainDialog(mContext);
            return;
        }
        if(klgCardDialog!=null&&klgCardDialog.isShowing()){
            klgCardDialog.dismiss();
        }
        if(klgCommonBeanList!=null&&klgCommonBeanList.size()>0){
            showKnowledgeCardDialog(mContext,klgCommonBeanList.get(0),isRetractCard,hasCustomBtn,listener,hasSave,hasNote,"");
            if(klgCommonBeanList.size()==1){
                img_arrorLeft.setVisibility(View.INVISIBLE);
                img_arrorRight.setVisibility(View.INVISIBLE);
            }else{
                img_arrorLeft.setVisibility(View.INVISIBLE);
                img_arrorRight.setVisibility(View.VISIBLE);
                img_arrorLeft.setTag(klgCommonBeanList);
                img_arrorRight.setTag(klgCommonBeanList);
            }
        }else {
            showNoKlgDetailsDialog(mContext);
        }

    }

    /**
     * 来源于课前预习的对接定制
     * @param mContext
     * @param klgCommonBeanList
     */
    public void showMoreKnowledgeCardDialog(final Context mContext, final List<KlgCommonBean> klgCommonBeanList, final boolean isRetractCard, boolean hasCustomBtn,int fromType ,final KlgCardDismissListener listener){
        if(klgCommonBeanList!=null&&fromType==0){
            for (KlgCommonBean klgCommonBean:klgCommonBeanList){
                if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    klgCommonBean.setUn_voice(KlgCourseWareManager.getMediaUrl(mContext)+""+klgCommonBean.getUn_voice());
                }
                if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    klgCommonBean.setUs_voice(KlgCourseWareManager.getMediaUrl(mContext)+""+klgCommonBean.getUs_voice());
                }
                if(TextUtils.isEmpty(klgCommonBean.getExplain())){
                    klgCommonBean.setExplain(mContext.getString(R.string.klg_no_meaning));
                    klgCommonBean.setHideBtn(true);
                }else{
                    klgCommonBean.setExplain(Html.fromHtml(klgCommonBean.getExplain()).toString().trim());
                }
            }
        }
        showMoreKnowledgeCardDialog(mContext,klgCommonBeanList,isRetractCard,hasCustomBtn,listener);
    }



    /**
     * @param mContext
     * @param klgCommonBean
     * @param convertView
     * @param isRetractCard
     */
    private void showFayinStyle(final Context mContext, final KlgCommonBean klgCommonBean, View convertView,final boolean isRetractCard){
        TextView tv_klgName = inflate.findViewById(R.id.tv_klg_name);
        tv_klgName.setText(klgCommonBean.getKlgName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tv_klgName.setLetterSpacing(0.04f);
        }
        //知识点发音
        if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
            convertView.findViewById(R.id.ll_fayin).setVisibility(View.GONE);
        }else{
            if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                convertView.findViewById(R.id.ll_un_phonetic).setVisibility(View.GONE);
            }else{
                TextView tv_unPhonetic = convertView.findViewById(R.id.tv_un_phonetic);
                try{
                    Typeface typeFace = Typeface.createFromAsset(mContext.getAssets(), "klg_droid_sans_bold.ttf");
                    tv_unPhonetic.setTypeface(typeFace);
                }catch (Exception e){

                }
                if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())){
                    tv_unPhonetic.setText(mContext.getString(R.string.klg_un));
                }else{
                    tv_unPhonetic.setText(mContext.getString(R.string.klg_un)+" "+ klgCommonBean.getUn_phonetic());
                }

                if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    convertView.findViewById(R.id.ll_un_phonetic).setTag(klgCommonBean.getUn_voice());
                    ll_unPhonetic = convertView.findViewById(R.id.ll_un_phonetic);
                    ll_unPhonetic.setOnClickListener(this);
                }else{
                    convertView.findViewById(R.id.img_un_phonetic).setVisibility(View.GONE);
                }
            }
            if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                convertView.findViewById(R.id.ll_us_phonetic).setVisibility(View.GONE);
            }else{
                TextView tv_usPhonetic = convertView.findViewById(R.id.tv_us_phonetic);
                if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())){

                    tv_usPhonetic.setText(mContext.getString(R.string.klg_us));
//                        convertView.findViewById(R.id.tv_us_phonetic).setVisibility(View.GONE);
                }else{
                    tv_usPhonetic.setText(mContext.getString(R.string.klg_us)+" "+ klgCommonBean.getUs_phonetic());
                }
                try{
                    Typeface typeFace = Typeface.createFromAsset(mContext.getAssets(), "klg_droid_sans_bold.ttf");
                    tv_usPhonetic.setTypeface(typeFace);
                }catch (Exception e){

                }
                if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    ll_usPhonetic = convertView.findViewById(R.id.ll_us_phonetic);
                    ll_usPhonetic.setTag(klgCommonBean.getUs_voice());
                    ll_usPhonetic.setOnClickListener(this);
                }else{
                    convertView.findViewById(R.id.img_us_phonetic).setVisibility(View.GONE);
                }
            }
        }
        TextView tv_retractCard = convertView.findViewById(R.id.tv_retract_card);
        tv_retractCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(System.currentTimeMillis()-time<500){
                    return;
                }
                time=System.currentTimeMillis();
                dissMissType=2;
                if(klgCardDialog !=null&& klgCardDialog.isShowing()){
                    klgCardDialog.dismiss();
                }
                if(!isRetractCard){//进入知识点学习课件。。。
                    if(KlgCourseWareManager.getVipLimitState(mContext)){
                        KlgCourseWareManager.getInstance(). showTrainAgainDialog(mContext);
                        return;
                    }
                    KlgCourseWareMainActivity.launch(mContext,klgCommonBean.getKlgCode(),true);
                }
            }
        });
    }

    private void showWordMoreMessageStyle(final Context mContext,KlgCommonBean klgCommonBean,View convertView,final boolean isRetractCard){
        //知识点释义
        if(klgCommonBean.getExplain()==null||TextUtils.isEmpty(klgCommonBean.getExplain())||TextUtils.equals("null",klgCommonBean.getExplain())){
            convertView.findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_meaning).setVisibility(View.GONE);
        }else {
            Log.e("aaaaaa","释义："+klgCommonBean.getExplain());
            tv_explain = convertView.findViewById(R.id.tv_meaning);
            tv_explain.setVisibility(View.VISIBLE);
            tv_explain.setText(klgCommonBean.getExplain());
            if(klgCommonBean.isShowMoreMeaning()&&!TextUtils.isEmpty(klgCommonBean.getShortExplan())){
                tv_explain.setText(klgCommonBean.getShortExplan());
                convertView.findViewById(R.id.tv_more).setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.tv_more).setTag(klgCommonBean.getExplain());
                convertView.findViewById(R.id.tv_more).setOnClickListener(this);
            }else {
                tv_explain.setText(klgCommonBean.getExplain());
                convertView.findViewById(R.id.tv_more).setVisibility(View.GONE);
            }

        }
        //句型
        if(klgCommonBean.getParaphrase()==null||TextUtils.isEmpty(klgCommonBean.getParaphrase())||TextUtils.equals("null",klgCommonBean.getParaphrase())){
            convertView.findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_sentence_pattern).setVisibility(View.GONE);
        }else{
            Log.e("aaaaaa","句型："+klgCommonBean.getParaphrase());
            TextView tv_sentence = convertView.findViewById(R.id.tv_sentence_pattern);
            tv_sentence.setText(klgCommonBean.getParaphrase());
        }
        //用法
        if(TextUtils.isEmpty(klgCommonBean.getUsage())){

            convertView.findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_usage_analysis).setVisibility(View.GONE);
        }else{
            Log.e("aaaaaa","用法："+klgCommonBean.getUsage());
            TextView tv_usageAnalysis = convertView.findViewById(R.id.tv_usage_analysis);
            tv_usageAnalysis.setText(klgCommonBean.getUsage());
        }
        //例句
        if(TextUtils.isEmpty(klgCommonBean.getClassicSen())){
            convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
        }else{
            convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.VISIBLE);
            tv_sentenceStructures = convertView.findViewById(R.id.tv_sentence_structures);
            TextView tv_sentenceStructureChinese = convertView.findViewById(R.id.tv_sentence_structures_chinese);
            SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
            SpannableString ss_content=new SpannableString(Html.fromHtml(klgCommonBean.getClassicSen().replace("font color='#0077f0'","font color='#64a9d0'")));
            spannableStringBuilder.append(ss_content);
            tv_sentenceStructureChinese.setText(klgCommonBean.getClassicTrain());
            if(!TextUtils.isEmpty(klgCommonBean.getClassicVoice())){
                ll_sentenceStructures= convertView.findViewById(R.id.ll_sentence_structures);
                ll_sentenceStructures .setTag(klgCommonBean.getClassicVoice());
                convertView.findViewById(R.id.ll_sentence_structures).setOnClickListener(this);
                String imgSpanStr="  lpl";
                SpannableString ss_volume=new SpannableString(imgSpanStr);
                Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.klg_volume_cyan_4);
                if(centerAlignImageSpan==null){
                    centerAlignImageSpan = new VolumeAlignImageSpan(mContext,bitmap);
                }else{
                    centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
                }
                ss_volume.setSpan(centerAlignImageSpan,imgSpanStr.length()-3,imgSpanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(ss_volume);
                SpannableString ss_end=new SpannableString("1");
                ss_end.setSpan(new ForegroundColorSpan(Color.TRANSPARENT),0,1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(ss_end);
            }
            tv_sentenceStructures.setText(spannableStringBuilder);
        }
        if(TextUtils.equals("ESP",klgCommonBean.getKlgType())){
            inflate.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
            if(!TextUtils.isEmpty(klgCommonBean.getClassicSen())){
                ViewStub viewStub = inflate.findViewById(R.id.viewstub_train_picture);
                if(viewStub!=null){
                    viewStub.inflate();
                    inflate.findViewById(R.id.tv_picture_explain).setVisibility(View.GONE);
                    final ImageView img_picture = inflate.findViewById(R.id.img_picture);
//                    Glide.with(mContext).load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen()).into(img_picture);
                    Glide.with(mContext).asBitmap().load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen())
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                            resource.
                                    int width = resource.getWidth();//图片原始宽度
                                    int height = resource.getHeight();//图片原始高度
                                    int scaledW = KlgToolUtils.dip2px(mContext,180f);//固定图片展示高度为180dp
                                    int scaledH = (height * scaledW) /width ;//计算出按比缩放后的宽度
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(scaledW, scaledH);
                                    img_picture.setLayoutParams(lp);
                                    img_picture.setImageBitmap(resource);

                                }
                            });
                }
                inflate.findViewById(R.id.img_picture).setVisibility(View.VISIBLE);
            }
        }else{
            if(inflate.findViewById(R.id.img_picture)!=null){
                inflate.findViewById(R.id.img_picture).setVisibility(View.GONE);
            }
            downloadPhonetic(mContext,klgCommonBean.getClassicVoice(),2,!isRetractCard);
        }
        downloadPhonetic(mContext,klgCommonBean.getUs_voice(),0,!isRetractCard);
        downloadPhonetic(mContext,klgCommonBean.getUn_voice(),1,!isRetractCard);
    }

    private void showFayinViewStyle(Context mContxt,View convertView){
        TextView tv_usPhoneTic = convertView.findViewById(R.id.tv_us_phonetic);
        TextView tv_unPhoneTic = convertView.findViewById(R.id.tv_un_phonetic);
        tv_unPhoneTic.setTextColor(Color.parseColor("#dce6fd"));
        tv_usPhoneTic.setTextColor(Color.parseColor("#dce6fd"));
        int fayinTextSize=KlgToolUtils.isPad(mContxt)?15:13;
        tv_unPhoneTic.setTextSize(fayinTextSize);
        tv_usPhoneTic.setTextSize(fayinTextSize);
        img_usPhonetic = convertView.findViewById(R.id.img_us_phonetic);
        img_unPhonetic = convertView.findViewById(R.id.img_un_phonetic);
        LinearLayout.LayoutParams layoutParams_unPhonetic = (LinearLayout.LayoutParams) img_unPhonetic.getLayoutParams();
        LinearLayout.LayoutParams layoutParams_usPhonetic = (LinearLayout.LayoutParams) img_usPhonetic.getLayoutParams();
        int dp5=KlgToolUtils.dip2px(mContxt,5);
        layoutParams_unPhonetic.rightMargin=dp5;
        layoutParams_usPhonetic.rightMargin=dp5;
        img_unPhonetic.setLayoutParams(layoutParams_unPhonetic);
        img_usPhonetic.setLayoutParams(layoutParams_usPhonetic);

    }

    private void showWordMsgViewStyle(Context mContext, View convertView){
        convertView.findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
        img_senPhonetic=convertView.findViewById(R.id.img_sentence_strutures);
        img_senPhonetic.setVisibility(View.GONE);
        int dp24=KlgToolUtils.dip2px(mContext,18);
        int dp6=KlgToolUtils.dip2px(mContext,6);
        int textSize=KlgToolUtils.isPad(mContext)?18:14;
        TextView tv_more = convertView.findViewById(R.id.tv_more);
        tv_more.setPadding(0,0,0,dp6);
        tv_more.setTextSize(textSize);
        TextView tv_meaning = convertView.findViewById(R.id.tv_meaning);
        tv_meaning.setPadding(0,dp24,0,tv_more.getVisibility()==View.VISIBLE?0:dp6);
        tv_meaning.setTextColor(Color.parseColor("#333333"));
        tv_meaning.setTextSize(textSize);
        TextView tv_sentencePattern = convertView.findViewById(R.id.tv_sentence_pattern);
        tv_sentencePattern.setPadding(0,dp24,0,dp6);
        tv_sentencePattern.setTextColor(Color.parseColor("#333333"));
        tv_sentencePattern.setTextSize(textSize);
        TextView tv_usageAnalysis =convertView.findViewById(R.id.tv_usage_analysis);
        tv_usageAnalysis.setPadding(0,dp24,0,dp6);
        tv_usageAnalysis.setTextColor(Color.parseColor("#333333"));
        tv_usageAnalysis.setTextSize(textSize);
        TextView tv_sentenceStructures =convertView.findViewById(R.id.tv_sentence_structures);
        tv_sentenceStructures.setTextColor(Color.parseColor("#333333"));
        tv_sentenceStructures.setTextSize(textSize);
        TextView tv_sentenceStructuresChinese =convertView.findViewById(R.id.tv_sentence_structures_chinese);
        tv_sentenceStructuresChinese.setTextColor(Color.parseColor("#575757"));
        tv_sentenceStructuresChinese.setTextSize(textSize);

        convertView.findViewById(R.id.ll_sentence_structures).setPadding(0,dp24,0,dp6);
        LinearLayout ll_wordMsgDetails = convertView.findViewById(R.id.ll_word_msg_details);
        int paddingDp = KlgToolUtils.dip2px(mContext, 10);
        ll_wordMsgDetails.setPadding(paddingDp,0,paddingDp*2,0);

    }

    private void updateCollectionState(Context mContext,KlgCommonBean commonBean,View inflate){
        ImageView img_save = inflate.findViewById(R.id.img_save);
        img_save.setImageResource(commonBean.getIsCollectWord()==1?R.mipmap.klg_icon_save_blue:R.mipmap.klg_icon_save_white);
    }


    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-time<500){
            return;
        }
        time=System.currentTimeMillis();
        String brand = Build.BRAND;
        Log.e("aaaaaaa","brand:"+brand);
        int id=v.getId();
        if(id==R.id.ll_un_phonetic){//英式
            String url = (String) v.getTag();
            playSound(url,img_unPhonetic);
        }else if(id==R.id.ll_us_phonetic){//美式
            String url = (String) v.getTag();
            playSound(url,img_usPhonetic);
        }else if(id==R.id.ll_sentence_structures){//例句
            String url = (String) v.getTag();
            playSound(url,img_senPhonetic);
        }else if(id==R.id.tv_more){
            v.setVisibility(View.GONE);
            String explain = (String) v.getTag();
            if(tv_explain!=null){
                tv_explain.setText(explain);
            }
        }else if(id==R.id.img_arror_left){
            List<KlgCommonBean> klgCommonBeanList= (List<KlgCommonBean>) v.getTag();
            if(klgCommonBeanList==null){
                return;
            }
            if(currentKlgIndex==1){
                v.setVisibility(View.INVISIBLE);
            }
            img_arrorRight.setVisibility(View.VISIBLE);
            currentKlgIndex--;
            if(inflate!=null){
                showFayinStyle(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                showWordMoreMessageStyle(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                updateCollectionState(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate);
            }
            pause();
        }else if(id==R.id.img_arror_right){
            List<KlgCommonBean> klgCommonBeanList= (List<KlgCommonBean>) v.getTag();
            if(klgCommonBeanList==null){
                return;
            }
            if(currentKlgIndex==klgCommonBeanList.size()-2){
                v.setVisibility(View.INVISIBLE);
            }
            img_arrorLeft.setVisibility(View.VISIBLE);
            currentKlgIndex++;
            if(inflate!=null){
                showFayinStyle(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                showWordMoreMessageStyle(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                updateCollectionState(v.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate);
            }
            pause();
        }else if(id==R.id.img_save){//点击收藏

        }else if(id==R.id.img_close_x){//关闭
            dissMissType=0;
            if(klgCardDialog !=null&& klgCardDialog.isShowing()){
                klgCardDialog.dismiss();
            }
        }
    }

    /**
     * 开启音频播放
     * @param url 音频url
     * @param img imgView
     */
    private void playSound(String url,final ImageView img){
//        url="https://lgresv57.obs.cn-south-1.myhuaweicloud.com/LGFTP/EspKnowledge/SpiderMaterial/English/Audio/G/20190323130325700.mp3";
        Log.e("aaaaa","playSound url:"+url);
        if(klgMediaManager==null){
            klgMediaManager = new KlgMediaManager(img.getContext());
        }
        controlImgAnimation(false,false,false);
        klgMediaManager.setUpMedia(KlgUrlEncodeUtils.urlencodChange(url), new KlgMediaManager.OnPlayListener() {

            @Override
            public void onComplete() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onStartError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onResumePlay() {

            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(klgMediaManager!=null){
                    klgMediaManager.start();
                }
                controlImgAnimation(img==img_usPhonetic,img==img_unPhonetic,img==img_senPhonetic);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });
    }

    /**
     * 设置动画
     * @param img
     * @param isAnimation
     */
    protected void volumeAnimationControl(ImageView img, boolean isAnimation){
        if( Looper.myLooper() != Looper.getMainLooper()){
            return;
        }
        if(img!=null&&img.getVisibility()== View.VISIBLE){
            if(isAnimation){
//                img.setImageResource(R.drawable.lgklg_animation_list_volume_cyan);
                img.setBackground(null);
                ((AnimationDrawable)img.getDrawable()).start();
            }else{
//                img.setImageResource(R.drawable.lgklg_volume_cyan_3);
                ((AnimationDrawable)img.getDrawable()).stop();
                ((AnimationDrawable)img.getDrawable()).selectDrawable(0);
                img.setBackgroundResource(R.drawable.klg_volume_cyan_3);

            }
        }
    }

    /**
     * 控制美式，英式，例句播放动画
     */
    private void controlImgAnimation(boolean isOpend,boolean isOpen1,boolean isOpend2){
        volumeAnimationControl(img_usPhonetic,isOpend);
        volumeAnimationControl(img_unPhonetic,isOpen1);
        volumeAnimationControl(img_senPhonetic,isOpend2);
        if(centerAlignImageSpan==null){
            return;
        }
        if(isOpend2){
            centerAlignImageSpan.startVolumeAnimation(tv_sentenceStructures);
        }else{
            centerAlignImageSpan.stopVolumeAnimation(tv_sentenceStructures);
        }
    }


    /**
     * 暂停
     */
    public void pause(){
        if(klgMediaManager!=null){
            klgMediaManager.pause();
        }
        controlImgAnimation(false,false,false);
//        volumeAnimationControl(img_usPhonetic,false);
//        volumeAnimationControl(img_unPhonetic,false);
//        volumeAnimationControl(img_senPhonetic,false);


    }

    /**
     * 销毁
     */
    public void release(){
        if(klgMediaManager!=null){
            klgMediaManager.release();
            klgMediaManager=null;
        }
        if(centerAlignImageSpan!=null&&tv_sentenceStructures!=null){
            centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
        }
    }


    public interface KlgCardDismissListener{
        void onCardDismiss(int dismissType, int position, KlgCommonBean klgCommonBean, KlgCollectionWordCallBack callBack);
    }

    public interface KlgCollectionWordCallBack{
        void updateCollectionState(int state);
    }

    public void openKlgDialog(final Context mContext,String klgCode){
        openKlgDialog(mContext,klgCode, KlgDbConstant.klg_baseUrl,false);

    }

    public void openKlgDialog(Context mContext,String klgCode,String url,boolean haiCustomBtn){
//        klgCode="CE0300000A0uK00G0";
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
            SharedPreferences sharedPreferences = mContext.getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(KlgDbConstant.SP_KNOWLEDGE_COURSE_URL, url);
            edit.commit();
        }
        getKlgConfig(mContext,klgCode,haiCustomBtn,true,false,false,null,"");
    }

    public void openKlgDialog(Context mContext,String klgCode,String url,boolean haiCustomBtn,String customBtnName){
//        klgCode="CE0300000A0uK00G0";
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
            SharedPreferences sharedPreferences = mContext.getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(KlgDbConstant.SP_KNOWLEDGE_COURSE_URL, url);
            edit.commit();
        }
        getKlgConfig(mContext,klgCode,haiCustomBtn,true,false,false,null,customBtnName);
    }

    /**
     * 电子教材库专用
     * @param mContext
     * @param klgCode
     * @param url
     */
    public void openKlgDialog(Context mContext,String klgCode,String url,boolean isOpenNote,
                              boolean isOpenCollection,KlgCardDismissListener listener){
//        klgCode="CE0300000A0uK00G0";
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
            SharedPreferences sharedPreferences = mContext.getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(KlgDbConstant.SP_KNOWLEDGE_COURSE_URL, url);
            edit.commit();
        }
        getKlgConfig(mContext,klgCode,false,true,isOpenNote,isOpenCollection,listener,"");
    }


    /**
     * 电子素材、过关训练阅读专用
     * @param mContext
     * @param klgCode
     * @param url
     * @param haiCustomBtn
     * @param customBtnName
     * @param customBtnClickListener
     */
    public void openKlgDialog(Context mContext,String klgCode,String url,boolean haiCustomBtn,String customBtnName,CustomBtnClickListener customBtnClickListener){
        Log.e("aaaa","KlgCode:"+klgCode);
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
        }
        KlgDbConstant.mediaUrl="";
        if(customBtnClickListener!=null){
            mCustomBtnClickListener=customBtnClickListener;
        }
//        openKlgDialog(mContext,klgCode,url,haiCustomBtn);
        getKlgConfig(mContext,klgCode,haiCustomBtn,true,false,false,null,customBtnName);
    }


    public void openKlgDialog(Context mContext,String klgCode,String url,String mediaUrl,boolean haiCustomBtn){
        if(!TextUtils.isEmpty(mediaUrl)){
            Log.e("aaaaaaaaaaaa","mediaUlr:"+mediaUrl.substring(mediaUrl.length()-1));
            if(TextUtils.equals("/",mediaUrl.substring(mediaUrl.length()-1))){
                KlgDbConstant.mediaUrl=mediaUrl;
            }else{
                KlgDbConstant.mediaUrl=mediaUrl+"/";
            }

        }else{
            KlgDbConstant.mediaUrl="";
        }
        openKlgDialog(mContext,klgCode,url,haiCustomBtn);
    }

    public void getKlgConfig(final Context mContext,final String klgCode,final boolean hasCustomBtn,boolean haiVipLimit,
                             final boolean isOpenNote,final boolean isOpenCollection,final KlgCardDismissListener listener,String customBtnName){
        if(System.currentTimeMillis()-time<300){
            return;
        }
        time=System.currentTimeMillis();
        if(haiVipLimit&&KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.getInstance().showTrainAgainDialog(mContext);
            return;
        }
        if(isLoad){
            return;
        }
        isLoad=true;
        if(loadingDailog==null){
            LoadingDailog.Builder builder = new LoadingDailog.Builder(mContext);
            builder.setShowMessage(false);
            builder.setCancelable(true);
            loadingDailog = builder.create();
            loadingDailog.show();
            loadingDailog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    RxApiManager.getInstance().removeAll();
                    isLoad=false;
                }
            });
            Window window = loadingDailog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.dimAmount=0.35f;

            window.setAttributes(attributes);
            RxApiManager.getInstance().removeAll();
        }else{
            if(!loadingDailog.isShowing()){
                loadingDailog.show();
            }
        }
        getVersionControl(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
    }

    private void getVersionControl(final Context mContext,final String klgCode,final boolean hasCustomBtn,
                                   final boolean isOpenNote,final boolean isOpenCollection,final KlgCardDismissListener listener,
                                   final String customBtnName){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getKlgVersion().compose(NetworkTransformer.<String>commonSchedulers()).
                subscribeWith(new NormalSubscriber<String>(){
                    @Override
                    public void onNext(String stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        Log.e("aaaaaaaa","onNext:"+stringKlgApiResponse);
                        if(TextUtils.equals("v5.4",stringKlgApiResponse)){
                            getKnowledgeConfigMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                        }else{
                            getV56VersionConfigMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaaaaa","onError:"+e.toString());
                        getKnowledgeConfigMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
//                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }

    private void getKnowledgeConfigMsg(final Context mContext,final String klgCode,final boolean hasCustomBtn,
                                       final boolean isOpenNote,final boolean isOpenCollection,final KlgCardDismissListener listener,
                                       final String customBtnName){
        Disposable disposable= Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getPlatFormConfigure().compose(NetworkTransformer.<KlgApiResponse<ResourcePlatFormConfigure>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<ResourcePlatFormConfigure>>(){
                    @Override
                    public void onNext(KlgApiResponse<ResourcePlatFormConfigure> stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse.getState()==1){
                            if(TextUtils.isEmpty( KlgDbConstant.mediaUrl)){
                                KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getData().getHttpIP()+":"+stringKlgApiResponse.getData().getHttpPort()+"/";
                            }
                            currentKlgIndex=0;
                            if(TextUtils.isEmpty(klgCode)){
                                showNoKlgDetailsDialog(mContext);
                            }else {
                                String[] split = klgCode.split("\\|");
                                if(split.length<2){
                                    getKnowledgeNewCardMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                                }else{
                                    if(klgCommonBeanList==null){
                                        klgCommonBeanList=new ArrayList<>();
                                    }else {
                                        klgCommonBeanList.clear();
                                    }
                                    for (int i = 0; i <split.length ; i++) {
                                        getMoreKnowledgeNewCardMsg(mContext,split[i],hasCustomBtn,split.length,isOpenNote,isOpenCollection,
                                                listener,customBtnName);
                                    }
                                }
                            }
                        }else{
                            showNoKlgDetailsDialog(mContext);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showNoKlgDetailsDialog(mContext);
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }


    private void getV56VersionConfigMsg(final Context mContext,final String klgCode,final boolean hasCustomBtn,
                                        final boolean isOpenNote,final boolean isOpenCollection,final KlgCardDismissListener listener,
                                        final String customBtnName){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getObsConfig().compose(NetworkTransformer.<ObsConfigMsgBean>commonSchedulers()).
                subscribeWith(new NormalSubscriber<ObsConfigMsgBean>(){
                    @Override
                    public void onNext(ObsConfigMsgBean stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse!=null){
                            KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getBucketName()+"."+stringKlgApiResponse.getEndpoint()+"/";
                        }else{
                            getKnowledgeConfigMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                            return;
                        }
                        currentKlgIndex=0;
                        if(TextUtils.isEmpty(klgCode)){
                            showNoKlgDetailsDialog(mContext);
                        }else {
                            String[] split = klgCode.split("\\|");
                            if(split.length<2){
                                getKnowledgeNewCardMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                            }else{
                                if(klgCommonBeanList==null){
                                    klgCommonBeanList=new ArrayList<>();
                                }else {
                                    klgCommonBeanList.clear();
                                }
                                for (int i = 0; i <split.length ; i++) {
                                    getMoreKnowledgeNewCardMsg(mContext,split[i],hasCustomBtn,split.length,isOpenNote,isOpenCollection,listener,
                                            customBtnName);
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeConfigMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
//                        showNoKlgDetailsDialog(mContext);
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }

    private void getKnowledgeNewCardMsg(final Context mContext,final String klgCode,final boolean hasCustomBtn,final boolean isOpenNote,
                                        final boolean isOpenCollection,final KlgCardDismissListener listener,final String customBtnName){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        KLog.json(new Gson().toJson(englishCardSourceKlgApiResponse));
                        if(englishCardSourceKlgApiResponse.getState()==1){
                            showKnowledgeCardDialog(mContext,buidKlgCommonEntity(mContext,englishCardSourceKlgApiResponse.getData()),false,hasCustomBtn,listener,
                                    isOpenCollection,isOpenNote,customBtnName);
                        }else{
                            getKnowledgeCardMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeCardMsg(mContext,klgCode,hasCustomBtn,isOpenNote,isOpenCollection,listener,customBtnName);
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }
    private void getKnowledgeCardMsg(final Context mContext,String klgCode,final boolean hasCustomBtn,final boolean isOpenNote,
                                     final boolean isOpenCollection,final KlgCardDismissListener listener,final String customBtnName){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishOldCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        KLog.json(new Gson().toJson(englishCardSourceKlgApiResponse));
                        if(englishCardSourceKlgApiResponse.getState()==1){
                            showKnowledgeCardDialog(mContext,buidKlgCommonEntity(mContext,englishCardSourceKlgApiResponse.getData()),false,hasCustomBtn,listener
                                    ,isOpenCollection,isOpenNote,customBtnName);
                        }else{
                            showNoKlgDetailsDialog(mContext);
                        }
                        if(loadingDailog!=null&&loadingDailog.isShowing()){
                            loadingDailog.dismiss();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showNoKlgDetailsDialog(mContext);
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }

    private void getMoreKnowledgeNewCardMsg(final Context mContext,final String klgCode,final boolean hasCustomBtn,final int totalKlgCount,
                                            final boolean isOpenNote,final boolean isOpenCollection,final KlgCardDismissListener listener,
                                            final String customBtnName){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        currentKlgIndex++;
                        if(englishCardSourceKlgApiResponse.getState()==1&&englishCardSourceKlgApiResponse.getData()!=null){
                            KlgCommonBean bean = buidKlgCommonEntity(mContext, englishCardSourceKlgApiResponse.getData());
                            klgCommonBeanList.add(bean);
                        }
                        if(currentKlgIndex==totalKlgCount){
                            showMoreKnowledgeCardDialog(mContext,klgCommonBeanList,false,false,listener,isOpenCollection,isOpenNote);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        currentKlgIndex++;
                        if(currentKlgIndex==totalKlgCount){
                            showMoreKnowledgeCardDialog(mContext,klgCommonBeanList,false,false,listener,isOpenCollection,isOpenNote);
                        }
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }

    /**
     * 构造知识点课件数据公共模型
     * @param cardSource
     * @return
     */
    private KlgCommonBean buidKlgCommonEntity(Context mContext,EnglishCardSource cardSource){
        if(cardSource==null){
            return null;
        }
        KlgCommonBean klgCommonBean=new KlgCommonBean();
        klgCommonBean.setKlgCode(cardSource.getKlgCode());
        klgCommonBean.setKlgName(cardSource.getKlgName());
        klgCommonBean.setKlgType(cardSource.getKlgType());
        if(cardSource.getWordData()!=null){
            klgCommonBean.setUn_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUN_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUN_voice())){
                klgCommonBean.setUn_voice( KlgDbConstant.mediaUrl+cardSource.getWordData().getUN_voice());
            }
            klgCommonBean.setUs_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUS_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUS_voice())){
                klgCommonBean.setUs_voice(KlgDbConstant.mediaUrl+cardSource.getWordData().getUS_voice());
            }
            if(TextUtils.equals("ESP",cardSource.getKlgType())){
                String picture=cardSource.getWordData().getClassicSen();
                if(!TextUtils.isEmpty(picture)&&picture.indexOf(".")!=-1){
                    String format = (picture.substring(picture.lastIndexOf(".") + 1)+"").toLowerCase();
                    if(TextUtils.equals(format,"bmp")||
                            TextUtils.equals(format,"jpg")||
                            TextUtils.equals(format,"gif")||
                            TextUtils.equals(format,"png")||
                            TextUtils.equals(format,"jpeg")){
                        klgCommonBean.setClassicSen(cardSource.getWordData().getClassicSen());
                    }
                }
//                klgCommonBean.setClassicSen(cardSource.getWordData().getClassicSen());
                if(cardSource.getWordData().getExplainList()!=null&&cardSource.getWordData().getExplainList().size()>5){
                    klgCommonBean.setShowMoreMeaning(true);
                    klgCommonBean.setShortExplan(buildExplainString(cardSource.getWordData().getExplainList(),false));
                }else{
                    klgCommonBean.setShowMoreMeaning(false);
                }
            }else{
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getWordData().getClassicSen()));
            }
            klgCommonBean.setClassicTrain(cardSource.getWordData().getClassicTran());
            if(!TextUtils.isEmpty(cardSource.getWordData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getWordData().getClassicVoice());
            }
            klgCommonBean.setExplain(buildExplainString(cardSource.getWordData().getExplainList(),true));
        }
        if(cardSource.getExpressionData()!=null&&cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
//            klgCommonBean.setExplain(cardSource.getExpressionData().getUsageList().get(0).getExplain().trim());
//            klgCommonBean.setUsage(cardSource.getExpressionData().getUsageList().get(0).getUsage());
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getExplain().trim());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setExplain(stringBuilder.toString());
            }
        }
        if(cardSource.getSyntaxData()!=null){
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicSen())){
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getSyntaxData().getClassicSen()));
            }

            klgCommonBean.setClassicTrain(cardSource.getSyntaxData().getClassicTran());
            klgCommonBean.setParaphrase(cardSource.getSyntaxData().getThemeName());
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getSyntaxData().getClassicVoice());
            }
            if(cardSource.getSyntaxData().getUsageList()!=null&&cardSource.getSyntaxData().getUsageList().size()>0){
//                klgCommonBean.setUsage(cardSource.getSyntaxData().getUsageList().get(0).getUsage());
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getSyntaxData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
        }

        return klgCommonBean;
    }

    /**
     * 构造释义内容
     * @param explainModelList
     * @return
     */
    private String buildExplainString(List<WordExplainModel> explainModelList,boolean max){
        StringBuffer explainString=new StringBuffer();
        int index=0;
        if(explainModelList!=null){
            for (WordExplainModel wordExplainModel:explainModelList){
                explainString.append(""+wordExplainModel.getCxAndExplain());
                if(index!=explainModelList.size()-1){
                    explainString.append("<br/>");
                }
                index++;
                if(!max&&index==5){
                    break;
                }
            }
            return Html.fromHtml(explainString.toString().replace("<&2&>","$&2&$")).toString().trim().replace("$&2&$","<&2&>");
        }else {
            return "";
        }
    }

    private String buildNewClassicSenString(String classicSen){
        if (TextUtils.isEmpty(classicSen)) {
            return classicSen;
        }
        String newString=classicSen.replaceAll("</STRONG>","</font>")
                .replaceAll("<STRONG>","<font color='#0077f0'>")
                .replaceAll("</strong>","</font>")
                .replaceAll("<strong>","<font color='#0077f0'>");
        return newString.trim();
    }

    private void downloadPhonetic(Context mContext,String url,final int urlType,boolean enableDownload){
        if(!enableDownload){
            return;
        }
        if(TextUtils.isEmpty(url)){
            return;
        }
        Disposable disposable = HttpDownManager.getInstance().downloadFile(url, Environment.getExternalStorageDirectory() +
                "/Android/data/" + mContext.getApplicationInfo().packageName + "/files/record/klgtemp", urlType+""+System.currentTimeMillis()+"."+url.substring(url.lastIndexOf(".") + 1, url.length()), new FileDownLoadObserver<File>() {
            @Override
            public void onDownLoadSuccess(File file) {
//                showTxtContent(file);
                if(urlType==0){
                    if(ll_usPhonetic!=null){
                        ll_usPhonetic.setTag(file.getPath());
                    }
                }else if(urlType==1){
                    if(ll_unPhonetic!=null){
                        ll_unPhonetic.setTag(file.getPath());
                    }
                }else{
                    if(ll_sentenceStructures!=null){
                        ll_sentenceStructures.setTag(file.getPath());
                    }
                }
            }

            @Override
            public void onDownLoadFail(Throwable throwable) {

            }

            @Override
            public void onProgress(long progress, long total) {

            }
        });
        RxApiManager.getInstance().add(disposable);
    }

    /**
     * 查询知识点失败弹窗
     */
    private void showNoKlgDetailsDialog(Context mContext){
        if(loadingDailog!=null&&loadingDailog.isShowing()){
            loadingDailog.dismiss();
        }
        View view=LayoutInflater.from(mContext).inflate(R.layout.klg_dialog_no_knowledge_meaning,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext,R.style.klg_NoBgColorStyle);//R.style.ImpKnDialogStyle
        builder.setView(view);
        klgCardDialog = builder.create();
        klgCardDialog.show();
//        knowledgeSimpleDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams attributes = klgCardDialog.getWindow().getAttributes();
        attributes.width=KlgToolUtils.dip2px(mContext,300);
        klgCardDialog.getWindow().setAttributes(attributes);
        KlgDbConstant.klg_baseUrl=mContext.getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE).getString(KlgDbConstant.SP_KNOWLEDGE_COURSE_URL, KlgDbConstant.klg_baseUrl);
        klgCardDialog.setOnDismissListener(dismissListener);
    }

    private DialogInterface.OnDismissListener dismissListener=new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            isLoad=false;
//            isShowBtn=false;
            if(klgMediaManager!=null){
                klgMediaManager.release();
                klgMediaManager=null;
            }
            if(loadingDailog!=null&&loadingDailog.isShowing()){
                loadingDailog.dismiss();
            }
        }
    };


    public interface CustomBtnClickListener{
        void onCustomBtnClick(KlgCommonBean klgCommonBean, View view);
    }


    /**
     * 专业化过关训练-阅读训练专用
     * @param mContext
     * @param klgCode
     * @param url
     * @param haiCustomBtn
     * @param customBtnName
     * @param customBtnClickListener
     */
    public void openKlgDialog(Context mContext,String klgCode,String url,boolean haiCustomBtn,
                              String customBtnName,CustomBtnClickListener customBtnClickListener,
                              String passTrainUrl,String trainSystem,String userID){
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
        }
        KlgDbConstant.mediaUrl="";
        if(customBtnClickListener!=null){
            mCustomBtnClickListener=customBtnClickListener;
        }
//
        getKlghaiInBook(klgCode,passTrainUrl,trainSystem,userID,mContext,url,customBtnName);
    }

    private void getKlghaiInBook(final String klgCode,String passTrainUrl,String trainSystem,String userID,
                                 final Context mContext,final String url,final String customBtnName){
        if(isLoad){
            return;
        }
        if(!(loadingDailog!=null&&loadingDailog.isShowing())){
            LoadingDailog.Builder builder = new LoadingDailog.Builder(mContext);
            builder.setShowMessage(false);
            builder.setCancelable(true);
            loadingDailog = builder.create();
            loadingDailog.show();
            loadingDailog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    RxApiManager.getInstance().removeAll();
                    isLoad=false;
                }
            });
            Window window = loadingDailog.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.dimAmount=0.35f;

            window.setAttributes(attributes);
            RxApiManager.getInstance().removeAll();
        }else {
            loadingDailog.show();
        }
        WordBookRequestBean bean=new WordBookRequestBean(klgCode,trainSystem,"123",userID);
        Disposable disposable=Network.getJsonData(PassTrainApi.class,passTrainUrl)
                .isInWorkBook(bean)
                .compose(NetworkTransformer.<PassTrainResponce>commonSchedulers())
                .subscribeWith(new NormalSubscriber<PassTrainResponce>(){

                    @Override
                    public void onNext(PassTrainResponce passTrainResponce) {
                        super.onNext(passTrainResponce);
                        boolean hasCustomTrain=true;
                        if(passTrainResponce.getStatus()==1){
                            hasCustomTrain=passTrainResponce.getData().getIsInWordBook()!=1;
                        }
                        openKlgDialog(mContext,klgCode,url,hasCustomTrain,customBtnName);
                        Log.e("aaaa","onNext");
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaa","onError");
                    }

                });
        RxApiManager.getInstance().add(disposable);
    }
}
